package com.youlai.boot.modules.comment.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.modules.comment.converter.CommentConverter;
import com.youlai.boot.modules.comment.mapper.CommentMapper;
import com.youlai.boot.modules.comment.model.Comment;
import com.youlai.boot.modules.comment.model.CommentForm;
import com.youlai.boot.modules.comment.model.CommentVO;
import com.youlai.boot.modules.comment.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private final CommentConverter commentConverter;

    @Override
    public Page<CommentVO> getCommentPage(Long userId, Long rootId, Integer status, int pageNum, int pageSize) {
        Page<CommentVO> page = new Page<>(pageNum, pageSize);
        Page<CommentVO> result = baseMapper.getCommentPage(page, userId, rootId, status);

        // 获取子评论
        result.getRecords().forEach(comment -> {
            List<CommentVO> children = baseMapper.getChildrenComments(comment.getId());
            comment.setChildren(children);
        });

        return result;
    }

    @Override
    public CommentVO getCommentById(Long id) {
        Comment comment = this.getById(id);
        CommentVO vo = commentConverter.toVO(comment);
        if (vo != null) {
            List<CommentVO> children = baseMapper.getChildrenComments(id);
            vo.setChildren(children);
        }
        return vo;
    }

    @Override
    public Long saveComment(CommentForm form) {
        Comment comment = commentConverter.toEntity(form);
        this.save(comment);
        return comment.getId();
    }

    @Override
    public void updateComment(CommentForm form) {
        Comment comment = commentConverter.toEntity(form);
        this.updateById(comment);
    }

    @Override
    public boolean deleteComment(Long id) {
        return this.removeById(id);
    }

    @Override
    public boolean likeComment(Long id) {
        return this.lambdaUpdate()
                .setSql("likes = likes + 1")
                .eq(Comment::getId, id)
                .update();
    }
}